<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>轮胎管理系统 - 费用结算</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入 jQuery 和 jQuery UI 用于自动补全 -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.0/themes/smoothness/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
    <style>
        .invoice-header {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .tire-item {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background-color: #fff;
            transition: all 0.3s ease;
        }
        .tire-item:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .tire-item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .cost-input {
            max-width: 150px;
        }
        .total-cost-section {
            background-color: #e9ecef;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
        }
        .invoice-preview {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 20px;
            background-color: white;
            margin-top: 20px;
            display: none;
        }
        .invoice-logo {
            text-align: center;
            margin-bottom: 20px;
        }
        .invoice-title {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
        }
        .invoice-details {
            margin-bottom: 20px;
        }
        .invoice-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .invoice-table th, .invoice-table td {
            border: 1px solid #dee2e6;
            padding: 8px;
            text-align: left;
        }
        .invoice-table th {
            background-color: #f8f9fa;
        }
        .invoice-total {
            text-align: right;
            font-weight: bold;
            font-size: 18px;
        }
        .invoice-footer {
            margin-top: 30px;
            text-align: center;
            font-size: 14px;
            color: #6c757d;
        }
        .btn-remove {
            color: #dc3545;
            background: none;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
        }
        .btn-remove:hover {
            color: #bd2130;
        }
        .autocomplete-list {
            position: absolute;
            background: white;
            border: 1px solid #ccc;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
            width: 100%;
            margin: 0;
            padding: 0;
            list-style: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .autocomplete-list li {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #eee;
        }
        .autocomplete-list li:hover {
            background-color: #f0f0f0;
        }
        .ui-autocomplete-loading {
            background: white url('') right center no-repeat;
            background-size: 16px 16px;
        }
        @media print {
            body * {
                visibility: hidden;
            }
            .invoice-preview, .invoice-preview * {
                visibility: visible;
            }
            .invoice-preview {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                border: none;
                box-shadow: none;
            }
            .no-print {
                display: none !important;
            }
        }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container">
        <a class="navbar-brand" href="/api/tires">轮胎管理系统</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires">轮胎列表</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires/batch-add">批量添加轮胎</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires/usage">查询使用记录</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires/visualization/">轮胎可视化</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires/statistics">轮胎统计</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/api/tires/cost-statistics">费用统计报表</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/api/tires/settlement">费用结算</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1>轮胎费用结算</h1>
        <div>
            <a href="/api/tires" class="btn btn-secondary">返回轮胎列表</a>
        </div>
    </div>

    <!-- 结算表单 -->
    <div class="card no-print">
        <div class="card-header">
            <h5 class="mb-0">费用结算信息</h5>
        </div>
        <div class="card-body">
            <form id="settlementForm">
                <div class="row mb-4">
                    <div class="col-md-4">
                        <label for="plateNumber" class="form-label">车牌号 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="plateNumber" name="plateNumber" required
                               placeholder="输入车牌号，支持自动补全">
                    </div>
                    <div class="col-md-4">
                        <label for="transportCompany" class="form-label">运输公司</label>
                        <select class="form-select" id="transportCompany" name="transportCompany">
                            <option value="">请选择运输公司</option>
                            <option th:each="company : ${transportCompanies}"
                                    th:value="${company}"
                                    th:text="${company}"></option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="settlementDate" class="form-label">结算日期</label>
                        <input type="date" class="form-control" id="settlementDate" name="settlementDate">
                    </div>
                </div>

                <div class="row mb-3">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5>轮胎费用明细</h5>
                            <button type="button" id="addTireBtn" class="btn btn-primary">添加轮胎</button>
                        </div>
                    </div>
                </div>

                <div id="tireItemsContainer">
                    <!-- 轮胎费用明细将通过JavaScript动态添加 -->
                </div>

                <div class="total-cost-section">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="remarks" class="form-label">备注</label>
                                <textarea class="form-control" id="remarks" name="remarks" rows="2" placeholder="请输入备注信息"></textarea>
                            </div>
                        </div>
                        <div class="col-md-6 text-end">
                            <h4>总计: <span id="totalCost">0.00</span> 元</h4>
                            <div class="mt-3">
                                <button type="button" id="previewInvoiceBtn" class="btn btn-info">预览结算单</button>
                                <button type="button" id="saveSettlementBtn" class="btn btn-success">保存结算记录</button>
                                <button type="button" id="printInvoiceBtn" class="btn btn-primary">打印结算单</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 结算单预览 -->
    <div class="invoice-preview" id="invoicePreview">
        <div class="invoice-logo">
            <h2>泰州卡友之家轮胎维修服务中心</h2>
            <p>轮胎费用结算单</p>
        </div>

        <div class="invoice-details">
            <div class="row">
                <div class="col-md-6">
                    <p><strong>车牌号:</strong> <span id="invoicePlateNumber"></span></p>
                    <p><strong>运输公司:</strong> <span id="invoiceTransportCompany"></span></p>
                </div>
                <div class="col-md-6 text-end">
                    <p><strong>结算日期:</strong> <span id="invoiceSettlementDate"></span></p>
                    <p><strong>结算单号:</strong> <span id="invoiceNumber"></span></p>
                </div>
            </div>
        </div>

        <table class="invoice-table">
            <thead>
            <tr>
                <th>序号</th>
                <th>轮胎号</th>
                <th>服务类型</th>
                <th>轮胎费用(元)</th>
                <th>服务费用(元)</th>
                <th>小计(元)</th>
                <th>备注</th>
            </tr>
            </thead>
            <tbody id="invoiceTireItems">
            <!-- 结算单轮胎明细将通过JavaScript动态填充 -->
            </tbody>
        </table>

        <div class="invoice-total">
            <p>总计: <span id="invoiceTotalCost">0.00</span> 元</p>
        </div>

        <div class="invoice-footer">
            <p>感谢您的惠顾，欢迎再次光临！</p>
            <p>联系电话: 13365207272 | 地址: 江苏省泰州市高港区疏港北路与环港大道交叉口南280米</p>
        </div>
    </div>

    <!-- 结算记录查询和统计区域 -->
    <div class="card mt-4 no-print">
        <div class="card-header">
            <h5 class="mb-0">结算记录查询</h5>
        </div>
        <div class="card-body">
            <form id="searchSettlementForm" class="row g-3">
                <div class="col-md-3">
                    <label for="searchPlateNumber" class="form-label">车牌号</label>
                    <input type="text" class="form-control" id="searchPlateNumber" name="plateNumber"
                           placeholder="输入车牌号">
                </div>
                <div class="col-md-3">
                    <label for="searchSettlementCompany" class="form-label">运输公司</label>
                    <select class="form-select" id="searchSettlementCompany" name="transportCompany">
                        <option value="">全部</option>
                        <option th:each="company : ${transportCompanies}"
                                th:value="${company}"
                                th:text="${company}"></option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="searchStartDate" class="form-label">开始日期</label>
                    <input type="date" class="form-control" id="searchStartDate" name="startDate">
                </div>
                <div class="col-md-2">
                    <label for="searchEndDate" class="form-label">结束日期</label>
                    <input type="date" class="form-control" id="searchEndDate" name="endDate">
                </div>
                <div class="col-md-2">
                    <label class="form-label">&nbsp;</label>
                    <div>
                        <button type="submit" class="btn btn-primary">查询</button>
                        <button type="button" id="resetSearchBtn" class="btn btn-secondary">重置</button>
                    </div>
                </div>
            </form>

            <!-- 统计信息 -->
            <div class="row mt-4" id="settlementStatistics">
                <div class="col-md-3">
                    <div class="card text-white bg-info">
                        <div class="card-body text-center">
                            <h5 class="card-title">总记录数</h5>
                            <p class="card-text display-6" id="totalRecords">0</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-white bg-success">
                        <div class="card-body text-center">
                            <h5 class="card-title">总金额</h5>
                            <p class="card-text display-6" id="totalAmount">0</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-white bg-warning">
                        <div class="card-body text-center">
                            <h5 class="card-title">补胎收入</h5>
                            <p class="card-text display-6" id="repairIncome">0</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-white bg-primary">
                        <div class="card-body text-center">
                            <h5 class="card-title">装胎收入</h5>
                            <p class="card-text display-6" id="installIncome">0</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 结算记录表格 -->
            <div class="table-responsive mt-4">
                <div id="loadingIndicator" class="text-center py-4" style="display: none;">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2 text-muted">正在加载数据...</p>
                </div>
                <table class="table table-striped table-hover">
                    <thead>
                    <tr>
                        <th>结算单号</th>
                        <th>车牌号</th>
                        <th>运输公司</th>
                        <th>结算日期</th>
                        <th>总金额</th>
                        <th>轮胎数量</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="settlementRecordsBody">
                    <!-- 初始加载状态 -->
                    <tr>
                        <td colspan="7" class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <p class="mt-2 text-muted">正在加载最新记录...</p>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<footer class="bg-dark text-white mt-5 py-4">
    <div class="container text-center">
        <p class="mb-0">轮胎管理系统 &copy; 2025</p>
    </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // 全局变量
    let autocompleteLists = {};

    $(document).ready(function() {
        // 检查 jQuery UI 是否加载
        if (typeof $.fn.autocomplete === 'undefined') {
            console.error('jQuery UI autocomplete 未加载！');
            // 使用原生实现
            initNativeAutocomplete();
        } else {
            console.log('jQuery UI autocomplete 已加载');
            initJQueryAutocomplete();
        }


        // 动态加载运输公司列表
        loadTransportCompanies();

        // 设置默认日期为今天
        const today = new Date().toISOString().split('T')[0];
        $('#settlementDate').val(today);

        // 设置查询默认日期范围为最近30天
        const endDate = new Date();
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - 30);

        $('#searchStartDate').val(startDate.toISOString().split('T')[0]);
        $('#searchEndDate').val(endDate.toISOString().split('T')[0]);

        // 结算记录查询表单提交事件
        $("#searchSettlementForm").submit(function(e) {
            e.preventDefault();
            searchSettlementRecords();
        });

        // 重置查询按钮事件
        $("#resetSearchBtn").click(function() {
            $("#searchSettlementForm")[0].reset();

            // 重置后设置默认日期范围
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(startDate.getDate() - 30);

            $('#searchStartDate').val(startDate.toISOString().split('T')[0]);
            $('#searchEndDate').val(endDate.toISOString().split('T')[0]);

            searchSettlementRecords();
        });

        // 添加轮胎按钮事件
        $("#addTireBtn").click(function() {
            addTireItem();
        });

        // 预览结算单按钮事件
        $("#previewInvoiceBtn").click(function() {
            previewInvoice();
        });

        // 保存结算记录按钮事件
        $("#saveSettlementBtn").click(function() {
            saveSettlement();
        });

        // 打印结算单按钮事件
        $("#printInvoiceBtn").click(function() {
            printInvoice();
        });

        // 初始添加一个轮胎项目
        addTireItem();

        // 初始加载结算记录
        searchSettlementRecords();
    });


    // 添加运输公司加载函数
    function loadTransportCompanies() {
        fetch('/api/tires/transport-companies')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(companies => {
                // 更新结算表单的运输公司下拉列表
                const companySelect = document.getElementById('transportCompany');
                const searchCompanySelect = document.getElementById('searchSettlementCompany');

                // 清空现有选项（除了默认选项）
                while (companySelect.options.length > 1) {
                    companySelect.remove(1);
                }
                while (searchCompanySelect.options.length > 1) {
                    searchCompanySelect.remove(1);
                }

                // 添加新的运输公司选项
                companies.forEach(company => {
                    const option1 = document.createElement('option');
                    option1.value = company;
                    option1.textContent = company;
                    companySelect.appendChild(option1);

                    const option2 = document.createElement('option');
                    option2.value = company;
                    option2.textContent = company;
                    searchCompanySelect.appendChild(option2);
                });

                console.log('加载运输公司列表成功，数量:', companies.length);
            })
            .catch(error => {
                console.error('加载运输公司列表失败:', error);
            });
    }

    // 使用 jQuery UI 的自动补全
    function initJQueryAutocomplete() {
        // 为结算表单车牌号输入框添加自动补全功能
        $("#plateNumber").autocomplete({
            source: function(request, response) {
                console.log("发送车牌号自动补全请求，关键词:", request.term);

                $.ajax({
                    url: "/api/tires/autocomplete/plate-numbers",
                    dataType: "json",
                    data: {
                        term: request.term
                    },
                    beforeSend: function() {
                        console.log("开始请求车牌号自动补全");
                        $("#plateNumber").addClass("ui-autocomplete-loading");
                    },
                    success: function(data) {
                        console.log("车牌号自动补全返回数据:", data);
                        console.log("返回数据数量:", data.length);
                        response(data);
                    },
                    error: function(xhr, status, error) {
                        console.error("车牌号自动补全请求失败:", error);
                        console.log("状态:", status);
                        console.log("响应文本:", xhr.responseText);
                        response([]);
                    },
                    complete: function() {
                        console.log("车牌号自动补全请求完成");
                        $("#plateNumber").removeClass("ui-autocomplete-loading");
                    }
                });
            },
            minLength: 1,
            delay: 300,
            select: function(event, ui) {
                console.log("用户选择了车牌号:", ui.item.value);
                $("#plateNumber").val(ui.item.value);
                return false;
            },
            focus: function(event, ui) {
                event.preventDefault();
            }
        });

        // 为查询表单车牌号输入框添加自动补全功能
        $("#searchPlateNumber").autocomplete({
            source: function(request, response) {
                console.log("发送查询车牌号自动补全请求，关键词:", request.term);

                $.ajax({
                    url: "/api/tires/autocomplete/plate-numbers",
                    dataType: "json",
                    data: {
                        term: request.term
                    },
                    beforeSend: function() {
                        console.log("开始请求查询车牌号自动补全");
                        $("#searchPlateNumber").addClass("ui-autocomplete-loading");
                    },
                    success: function(data) {
                        console.log("查询车牌号自动补全返回数据:", data);
                        console.log("返回数据数量:", data.length);
                        response(data);
                    },
                    error: function(xhr, status, error) {
                        console.error("查询车牌号自动补全请求失败:", error);
                        console.log("状态:", status);
                        console.log("响应文本:", xhr.responseText);
                        response([]);
                    },
                    complete: function() {
                        console.log("查询车牌号自动补全请求完成");
                        $("#searchPlateNumber").removeClass("ui-autocomplete-loading");
                    }
                });
            },
            minLength: 1,
            delay: 300,
            select: function(event, ui) {
                console.log("用户选择了查询车牌号:", ui.item.value);
                $("#searchPlateNumber").val(ui.item.value);
                return false;
            },
            focus: function(event, ui) {
                event.preventDefault();
            }
        });
    }

    // 使用原生 JavaScript 的自动补全
    function initNativeAutocomplete() {
        const plateNumberInput = document.getElementById('plateNumber');
        const searchPlateNumberInput = document.getElementById('searchPlateNumber');

        // 结算表单车牌号自动补全
        plateNumberInput.addEventListener('input', function(e) {
            const value = e.target.value.trim();

            // 清除之前的列表
            if (autocompleteLists['plateNumber']) {
                autocompleteLists['plateNumber'].remove();
                autocompleteLists['plateNumber'] = null;
            }

            if (value.length < 1) {
                return;
            }

            // 显示加载状态
            plateNumberInput.classList.add('ui-autocomplete-loading');

            // 发送请求
            fetch(`/api/tires/autocomplete/plate-numbers?term=${encodeURIComponent(value)}`)
                .then(response => response.json())
                .then(data => {
                    plateNumberInput.classList.remove('ui-autocomplete-loading');

                    if (data && data.length > 0) {
                        showAutocompleteList(data, plateNumberInput, 'plateNumber');
                    }
                })
                .catch(error => {
                    console.error('自动补全请求失败:', error);
                    plateNumberInput.classList.remove('ui-autocomplete-loading');
                });
        });

        // 查询表单车牌号自动补全
        searchPlateNumberInput.addEventListener('input', function(e) {
            const value = e.target.value.trim();

            // 清除之前的列表
            if (autocompleteLists['searchPlateNumber']) {
                autocompleteLists['searchPlateNumber'].remove();
                autocompleteLists['searchPlateNumber'] = null;
            }

            if (value.length < 1) {
                return;
            }

            // 显示加载状态
            searchPlateNumberInput.classList.add('ui-autocomplete-loading');

            // 发送请求
            fetch(`/api/tires/autocomplete/plate-numbers?term=${encodeURIComponent(value)}`)
                .then(response => response.json())
                .then(data => {
                    searchPlateNumberInput.classList.remove('ui-autocomplete-loading');

                    if (data && data.length > 0) {
                        showAutocompleteList(data, searchPlateNumberInput, 'searchPlateNumber');
                    }
                })
                .catch(error => {
                    console.error('查询自动补全请求失败:', error);
                    searchPlateNumberInput.classList.remove('ui-autocomplete-loading');
                });
        });

        // 点击页面其他区域时隐藏自动补全列表
        document.addEventListener('click', function(e) {
            for (let key in autocompleteLists) {
                if (autocompleteLists[key] &&
                    !autocompleteLists[key].contains(e.target) &&
                    e.target.id !== key) {
                    autocompleteLists[key].remove();
                    autocompleteLists[key] = null;
                }
            }
        });
    }

    // 显示自动补全列表
    function showAutocompleteList(items, inputElement, listKey) {
        // 移除现有列表
        if (autocompleteLists[listKey]) {
            autocompleteLists[listKey].remove();
        }

        // 创建列表
        const autocompleteList = document.createElement('ul');
        autocompleteList.className = 'autocomplete-list';

        // 添加列表项
        items.forEach(item => {
            const listItem = document.createElement('li');
            listItem.textContent = item;

            listItem.addEventListener('mouseenter', function() {
                this.style.backgroundColor = '#f0f0f0';
            });

            listItem.addEventListener('mouseleave', function() {
                this.style.backgroundColor = '';
            });

            listItem.addEventListener('click', function() {
                inputElement.value = item;
                autocompleteList.remove();
                autocompleteLists[listKey] = null;
            });

            autocompleteList.appendChild(listItem);
        });

        // 定位并显示列表
        const rect = inputElement.getBoundingClientRect();
        autocompleteList.style.top = (rect.bottom + window.scrollY) + 'px';
        autocompleteList.style.left = (rect.left + window.scrollX) + 'px';
        autocompleteList.style.width = rect.width + 'px';

        document.body.appendChild(autocompleteList);
        autocompleteLists[listKey] = autocompleteList;
    }

    // 添加轮胎费用项目
    function addTireItem() {
        const container = $("#tireItemsContainer");
        const index = container.children().length + 1;

        const tireItemHtml = `
      <div class="tire-item" id="tireItem${index}">
        <div class="tire-item-header">
          <h6 class="mb-0">轮胎 ${index}</h6>
          <button type="button" class="btn-remove" onclick="removeTireItem(${index})">×</button>
        </div>
        <div class="row g-3">
          <div class="col-md-3">
            <label for="tireNumber${index}" class="form-label">轮胎号</label>
            <input type="text" class="form-control tire-number" id="tireNumber${index}"
                   placeholder="输入轮胎号，支持自动补全">
          </div>
          <div class="col-md-3">
            <label for="serviceType${index}" class="form-label">服务类型</label>
            <select class="form-select service-type" id="serviceType${index}">
              <option value="repair">补胎</option>
              <option value="install">装胎</option>
              <option value="replace">换胎</option>
              <option value="inspection">检测</option>
              <option value="other">其他</option>
            </select>
          </div>
          <div class="col-md-2">
            <label for="tireCost${index}" class="form-label">轮胎费用(元)</label>
            <input type="number" class="form-control cost-input tire-cost" id="tireCost${index}"
                   value="0" min="0" step="0.01">
          </div>
          <div class="col-md-2">
            <label for="serviceCost${index}" class="form-label">服务费用(元)</label>
            <input type="number" class="form-control cost-input service-cost" id="serviceCost${index}"
                   value="0" min="0" step="0.01">
          </div>
          <div class="col-md-2">
            <label for="tireRemarks${index}" class="form-label">备注</label>
            <input type="text" class="form-control tire-remarks" id="tireRemarks${index}"
                   placeholder="轮胎备注">
          </div>
        </div>
      </div>
    `;

        container.append(tireItemHtml);

        // 为轮胎号输入框添加自动补全功能
        if (typeof $.fn.autocomplete !== 'undefined') {
            // 使用 jQuery UI
            $(`#tireNumber${index}`).autocomplete({
                source: function(request, response) {
                    console.log("发送轮胎号自动补全请求，关键词:", request.term);

                    $.ajax({
                        url: "/api/tires/autocomplete/tire-numbers",
                        dataType: "json",
                        data: {
                            term: request.term
                        },
                        beforeSend: function() {
                            console.log("开始请求轮胎号自动补全");
                            $(`#tireNumber${index}`).addClass("ui-autocomplete-loading");
                        },
                        success: function(data) {
                            console.log("轮胎号自动补全返回数据:", data);
                            console.log("返回数据数量:", data.length);
                            response(data);
                        },
                        error: function(xhr, status, error) {
                            console.error("轮胎号自动补全请求失败:", error);
                            console.log("状态:", status);
                            console.log("响应文本:", xhr.responseText);
                            response([]);
                        },
                        complete: function() {
                            console.log("轮胎号自动补全请求完成");
                            $(`#tireNumber${index}`).removeClass("ui-autocomplete-loading");
                        }
                    });
                },
                minLength: 1,
                delay: 300,
                select: function(event, ui) {
                    console.log("用户选择了轮胎号:", ui.item.value);
                    $(`#tireNumber${index}`).val(ui.item.value);
                    return false;
                },
                focus: function(event, ui) {
                    event.preventDefault();
                }
            });
        } else {
            // 使用原生实现
            initTireNumberAutocomplete(`tireNumber${index}`);
        }

        // 添加费用变化监听
        $(`#tireCost${index}, #serviceCost${index}`).on('input', calculateTotalCost);

        // 更新焦点选择行为
        $(`#tireNumber${index}`).focus(function() {
            $(this).select();
        });
    }

    // 初始化轮胎号自动补全
    function initTireNumberAutocomplete(inputId) {
        const inputElement = document.getElementById(inputId);

        inputElement.addEventListener('input', function(e) {
            const value = e.target.value.trim();

            if (autocompleteLists[inputId]) {
                autocompleteLists[inputId].remove();
                autocompleteLists[inputId] = null;
            }

            if (value.length < 1) {
                return;
            }

            inputElement.classList.add('ui-autocomplete-loading');

            fetch(`/api/tires/autocomplete/tire-numbers?term=${encodeURIComponent(value)}`)
                .then(response => response.json())
                .then(data => {
                    inputElement.classList.remove('ui-autocomplete-loading');

                    if (data && data.length > 0) {
                        showAutocompleteList(data, inputElement, inputId);
                    }
                })
                .catch(error => {
                    console.error('轮胎号自动补全请求失败:', error);
                    inputElement.classList.remove('ui-autocomplete-loading');
                });
        });
    }

    // 移除轮胎费用项目
    function removeTireItem(index) {
        if ($("#tireItemsContainer").children().length > 1) {
            $(`#tireItem${index}`).remove();
            // 重新计算总费用
            calculateTotalCost();
            // 重新编号轮胎项目
            renumberTireItems();
        } else {
            alert("至少需要保留一个轮胎项目");
        }
    }

    // 重新编号轮胎项目
    function renumberTireItems() {
        $("#tireItemsContainer .tire-item").each(function(index) {
            const newIndex = index + 1;
            $(this).attr("id", "tireItem" + newIndex);
            $(this).find(".tire-item-header h6").text("轮胎 " + newIndex);
            $(this).find(".btn-remove").attr("onclick", "removeTireItem(" + newIndex + ")");
        });
    }

    // 计算总费用
    function calculateTotalCost() {
        let total = 0;

        $(".tire-item").each(function() {
            const tireCost = parseFloat($(this).find(".tire-cost").val()) || 0;
            const serviceCost = parseFloat($(this).find(".service-cost").val()) || 0;
            total += tireCost + serviceCost;
        });

        $("#totalCost").text(total.toFixed(2));
        return total;
    }

    // 预览结算单
    function previewInvoice() {
        // 验证表单
        if (!$("#plateNumber").val()) {
            alert("请输入车牌号");
            $("#plateNumber").focus();
            return;
        }

        // 获取表单数据
        const plateNumber = $("#plateNumber").val();
        const transportCompany = $("#transportCompany").val();
        const settlementDate = $("#settlementDate").val();
        const remarks = $("#remarks").val();
        const totalCost = calculateTotalCost();

        // 生成结算单号
        const invoiceNumber = "INV" + new Date().getTime();

        // 更新结算单预览
        $("#invoicePlateNumber").text(plateNumber);
        $("#invoiceTransportCompany").text(transportCompany || "--");
        $("#invoiceSettlementDate").text(settlementDate);
        $("#invoiceNumber").text(invoiceNumber);
        $("#invoiceTotalCost").text(totalCost.toFixed(2));

        // 填充轮胎明细
        const invoiceTireItems = $("#invoiceTireItems");
        invoiceTireItems.empty();

        $(".tire-item").each(function(index) {
            const tireNumber = $(this).find(".tire-number").val() || "--";
            const serviceType = $(this).find(".service-type").val();
            const serviceTypeText = {
                'repair': '补胎',
                'install': '装胎',
                'replace': '换胎',
                'inspection': '检测',
                'other': '其他'
            }[serviceType];
            const tireCost = parseFloat($(this).find(".tire-cost").val()) || 0;
            const serviceCost = parseFloat($(this).find(".service-cost").val()) || 0;
            const subtotal = tireCost + serviceCost;
            const tireRemarks = $(this).find(".tire-remarks").val() || "--";

            const rowHtml = `
        <tr>
          <td>${index + 1}</td>
          <td>${tireNumber}</td>
          <td>${serviceTypeText}</td>
          <td>${tireCost.toFixed(2)}</td>
          <td>${serviceCost.toFixed(2)}</td>
          <td>${subtotal.toFixed(2)}</td>
          <td>${tireRemarks}</td>
        </tr>
      `;

            invoiceTireItems.append(rowHtml);
        });

        // 显示结算单预览
        $("#invoicePreview").show();

        // 滚动到结算单预览
        $('html, body').animate({
            scrollTop: $("#invoicePreview").offset().top
        }, 500);
    }

    // 保存结算记录
    function saveSettlement() {
        // 验证表单
        if (!$("#plateNumber").val()) {
            alert("请输入车牌号");
            $("#plateNumber").focus();
            return;
        }

        // 收集表单数据
        const settlementData = {
            plateNumber: $("#plateNumber").val(),
            transportCompany: $("#transportCompany").val(),
            settlementDate: $("#settlementDate").val(),
            remarks: $("#remarks").val(),
            tireItems: []
        };

        // 收集轮胎项目数据
        $(".tire-item").each(function() {
            const tireItem = {
                tireNumber: $(this).find(".tire-number").val(),
                serviceType: $(this).find(".service-type").val(),
                tireCost: parseFloat($(this).find(".tire-cost").val()) || 0,
                serviceCost: parseFloat($(this).find(".service-cost").val()) || 0,
                remarks: $(this).find(".tire-remarks").val()
            };

            settlementData.tireItems.push(tireItem);
        });

        // 发送数据到服务器
        fetch('/api/settlement/save', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(settlementData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('结算记录保存成功！结算单号: ' + data.invoiceNumber);
                    // 重置表单
                    $("#settlementForm")[0].reset();
                    $("#tireItemsContainer").empty();
                    addTireItem();
                    $("#invoicePreview").hide();

                    // 刷新结算记录列表
                    searchSettlementRecords();
                } else {
                    alert('保存结算记录失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('保存结算记录失败:', error);
                alert('保存结算记录失败，请重试');
            });
    }
/*
    // 打印结算单
    function printInvoice() {
        if ($("#invoicePreview").is(":visible")) {
            window.print();
        } else {
            alert("请先预览结算单");
        }
    }
*/
    // 查询结算记录
    function searchSettlementRecords() {
        const formData = new FormData(document.getElementById('searchSettlementForm'));
        const params = new URLSearchParams();

        let hasSearchCriteria = false;
        for (const [key, value] of formData.entries()) {
            if (value) {
                params.append(key, value);
                hasSearchCriteria = true;
            }
        }

        // 如果没有查询条件，添加参数获取最新5条记录
        if (!hasSearchCriteria) {
            params.append('limit', '5');
            params.append('sort', 'settlementDate,desc');
        }

        console.log('查询参数:', params.toString());

        fetch(`/api/settlement/records?${params}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                updateSettlementRecordsTable(data);
                // 加载统计信息
                loadSettlementStatistics();
            })
            .catch(error => {
                console.error('查询结算记录失败:', error);
                // 显示友好的错误信息
                const tbody = document.getElementById('settlementRecordsBody');
                tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-4">
                        <div class="text-danger">
                            <i class="fas fa-exclamation-triangle"></i> 加载数据失败，请稍后重试
                        </div>
                    </td>
                </tr>
            `;
            });
    }

    // 更新结算记录表格
    function updateSettlementRecordsTable(records) {
        const tbody = document.getElementById('settlementRecordsBody');
        tbody.innerHTML = '';

        if (!records || records.length === 0) {
            tbody.innerHTML = `
            <tr>
                <td colspan="7" class="text-center py-4">
                    <div class="text-muted">
                        <i class="fas fa-inbox"></i> 暂无结算记录
                    </div>
                </td>
            </tr>
        `;
            return;
        }

        try {
            records.forEach(record => {
                const row = document.createElement('tr');

                // 计算轮胎数量
                const tireCount = record.items ? record.items.length : 0;

                row.innerHTML = `
                <td>${record.invoiceNumber || '--'}</td>
                <td>${record.plateNumber || '--'}</td>
                <td>${record.transportCompany || '--'}</td>
                <td>${record.settlementDate || '--'}</td>
                <td>¥${record.totalCost ? record.totalCost.toFixed(2) : '0.00'}</td>
                <td>${tireCount}</td>
                <td>
                    <button class="btn btn-sm btn-info" onclick="viewSettlementDetail(${record.id})">查看</button>
                    <button class="btn btn-sm btn-warning" onclick="printSettlement(${record.id})">打印</button>
                </td>
            `;
                tbody.appendChild(row);
            });
        } catch (error) {
            console.error('更新表格时出错:', error);
            tbody.innerHTML = `
            <tr>
                <td colspan="7" class="text-center py-4">
                    <div class="text-danger">
                        <i class="fas fa-exclamation-triangle"></i> 数据显示异常
                    </div>
                </td>
            </tr>
        `;
        }
    }

    // 加载结算统计信息
    function loadSettlementStatistics() {
        const formData = new FormData(document.getElementById('searchSettlementForm'));
        const params = new URLSearchParams();

        for (const [key, value] of formData.entries()) {
            if (key === 'startDate' && value) params.append('startDate', value);
            if (key === 'endDate' && value) params.append('endDate', value);
        }

        fetch(`/api/settlement/statistics?${params}`)
            .then(response => response.json())
            .then(data => {
                updateSettlementStatistics(data);
            })
            .catch(error => {
                console.error('加载结算统计失败:', error);
            });
    }

    // 更新结算统计信息
    function updateSettlementStatistics(statistics) {
        document.getElementById('totalRecords').textContent = statistics.totalRecords || 0;
        document.getElementById('totalAmount').textContent = '¥' + (statistics.totalAmount || 0).toFixed(2);

        // 服务类型统计
        const serviceTypeStats = statistics.serviceTypeStats || {};
        document.getElementById('repairIncome').textContent = '¥' + (serviceTypeStats.repair || 0).toFixed(2);
        document.getElementById('installIncome').textContent = '¥' + (serviceTypeStats.install || 0).toFixed(2);
    }

    // 查看结算记录详情
    function viewSettlementDetail(recordId) {
        fetch(`/api/settlement/${recordId}`)
            .then(response => response.json())
            .then(record => {
                showSettlementDetailModal(record);
            })
            .catch(error => {
                console.error('获取结算记录详情失败:', error);
                alert('获取详情失败');
            });
    }

    // 显示结算记录详情模态框
    function showSettlementDetailModal(record) {
        // 创建模态框HTML
        const modalHtml = `
            <div class="modal fade" id="settlementDetailModal" tabindex="-1">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">结算记录详情 - ${record.invoiceNumber}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <p><strong>车牌号:</strong> ${record.plateNumber}</p>
                                    <p><strong>运输公司:</strong> ${record.transportCompany || '--'}</p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>结算日期:</strong> ${record.settlementDate}</p>
                                    <p><strong>总金额:</strong> ¥${record.totalCost.toFixed(2)}</p>
                                </div>
                            </div>
                            <div class="mb-3">
                                <p><strong>备注:</strong> ${record.remarks || '--'}</p>
                            </div>
                            <h6>轮胎明细</h6>
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>轮胎号</th>
                                        <th>服务类型</th>
                                        <th>轮胎费用</th>
                                        <th>服务费用</th>
                                        <th>小计</th>
                                        <th>备注</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${record.items ? record.items.map(item => `
                                        <tr>
                                            <td>${item.tireNumber}</td>
                                            <td>${getServiceTypeText(item.serviceType)}</td>
                                            <td>¥${item.tireCost.toFixed(2)}</td>
                                            <td>¥${item.serviceCost.toFixed(2)}</td>
                                            <td>¥${(item.tireCost + item.serviceCost).toFixed(2)}</td>
                                            <td>${item.remarks || '--'}</td>
                                        </tr>
                                    `).join('') : ''}
                                </tbody>
                            </table>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-primary" onclick="printSettlement(${record.id})">打印</button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // 添加模态框到页面
        $('body').append(modalHtml);

        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('settlementDetailModal'));
        modal.show();

        // 模态框关闭后移除
        $('#settlementDetailModal').on('hidden.bs.modal', function () {
            $(this).remove();
        });
    }

    // 获取服务类型文本
    function getServiceTypeText(serviceType) {
        const typeMap = {
            'repair': '补胎',
            'install': '装胎',
            'replace': '换胎',
            'inspection': '检测',
            'other': '其他'
        };
        return typeMap[serviceType] || serviceType;
    }

    // 打印结算单
    function printInvoice() {
        if ($("#invoicePreview").is(":visible")) {
            // 隐藏不需要打印的元素
            $(".no-print").hide();

            // 打印整个页面
            window.print();

            // 恢复显示
            setTimeout(() => {
                $(".no-print").show();
            }, 500);
        } else {
            alert("请先预览结算单");
        }
    }

    // 打印结算记录
    function printSettlement(recordId) {
        console.log("打印结算记录:", recordId);

        // 获取结算记录详情
        fetch(`/api/settlement/${recordId}`)
            .then(response => response.json())
            .then(record => {
                // 填充打印数据
                fillPrintData(record);

                // 显示打印预览
                $("#invoicePreview").show();

                // 滚动到打印预览区域
                $('html, body').animate({
                    scrollTop: $("#invoicePreview").offset().top
                }, 500, function() {
                    // 隐藏不需要打印的元素
                    $(".no-print").hide();

                    // 执行打印
                    window.print();

                    // 恢复显示
                    setTimeout(() => {
                        $(".no-print").show();
                        $("#invoicePreview").hide();
                    }, 500);
                });
            })
            .catch(error => {
                console.error('获取结算记录详情失败:', error);
                alert('获取结算记录详情失败，无法打印');
            });
    }

    // 填充打印数据
    function fillPrintData(record) {
        // 更新结算单预览
        $("#invoicePlateNumber").text(record.plateNumber || "--");
        $("#invoiceTransportCompany").text(record.transportCompany || "--");
        $("#invoiceSettlementDate").text(record.settlementDate || "--");
        $("#invoiceNumber").text(record.invoiceNumber || "--");
        $("#invoiceTotalCost").text(record.totalCost ? record.totalCost.toFixed(2) : "0.00");

        // 填充轮胎明细
        const invoiceTireItems = $("#invoiceTireItems");
        invoiceTireItems.empty();

        if (record.items && record.items.length > 0) {
            record.items.forEach((item, index) => {
                const serviceTypeText = getServiceTypeText(item.serviceType);
                const tireCost = item.tireCost || 0;
                const serviceCost = item.serviceCost || 0;
                const subtotal = tireCost + serviceCost;
                const tireRemarks = item.remarks || "--";

                const rowHtml = `
                <tr>
                    <td>${index + 1}</td>
                    <td>${item.tireNumber || "--"}</td>
                    <td>${serviceTypeText}</td>
                    <td>${tireCost.toFixed(2)}</td>
                    <td>${serviceCost.toFixed(2)}</td>
                    <td>${subtotal.toFixed(2)}</td>
                    <td>${tireRemarks}</td>
                </tr>
            `;
                invoiceTireItems.append(rowHtml);
            });
        }
    }
</script>
</body>
</html>